package com.nuoniu.sibanyun.service.so.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.entity.so.VSaleOrderDetail;
import com.nuoniu.sibanyun.mapper.so.VSaleOrderDetailMapper;
import com.nuoniu.sibanyun.service.so.IVSaleOrderDetailService;
import com.nuoniu.sibanyun.service.so.IVSaleOrderMainService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author baiqiang
 * @since 2020-11-26
 */
@Service
public class VSaleOrderDetailServiceImpl extends ServiceImpl<VSaleOrderDetailMapper, VSaleOrderDetail> implements IVSaleOrderDetailService {

    @Autowired
    @Lazy
    private IVSaleOrderMainService saleOrderMainService;


    @Override
    public void removeByOrderId(Long orderId) {
        baseMapper.removeByOrderId(orderId);
    }

    @Override
    public List<VSaleOrderDetail> getDetailsByOrderId(Long orderId) {
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("company_id",userInfo.getCompanyId());
        queryWrapper.eq("order_id",orderId);
        List<VSaleOrderDetail> list = list(queryWrapper);
        return list;
    }

    @Override
    public void updateOperationStatus(Integer voucherId) {
        baseMapper.updateOperationStatus(voucherId);
    }

    @Override
    public Integer getOperationCount(Integer orderId) {
        return baseMapper.getOperationCount(orderId);
    }

    @Override
    public List<VSaleOrderDetail> getList(Integer companyId) {
        return baseMapper.getList(companyId);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public boolean  updateGenerateWorkPlanStatus(Long saleOrderId, List<Long> detailIds, Integer status) {
        UserInfo userInfo = UserThreadLocal.get();
        //更新明细状态
        baseMapper.updateDetailGenerateWorkPlanStatus(userInfo.getCompanyId(),detailIds,status);
        //查询 除去 当前明细ID 意外的还没有生成 计划单的 明细数量
        Integer sumDetailNotNumber = baseMapper.sumDetailNotGenerateWorkPlanStatus(userInfo.getCompanyId(), saleOrderId, detailIds);
        // 如果 读取的状态 不同，则说明 明细 没有全部 更新为1
        if (0 == status )saleOrderMainService.updateGenerateWorkPlanStatus(saleOrderId,0);
        if (1 == status && 0 == sumDetailNotNumber ){
            saleOrderMainService.updateGenerateWorkPlanStatus(saleOrderId,1);
        }
        return false;
    }


}
